package com.ajie.bluetoothcard.ui;



import java.io.File;

import com.ajie.bluetoothcard.db.DBApi;
import com.ajie.bluetoothcard.domain.Card;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;


/**
 * @author liujie
 *  @Date: 2013-12-04
 * @version 1.0.0
 */
public class MainMyCardActivity extends BaseActivity implements OnCheckedChangeListener{
	private Button edit,send;
	private TextView name,mobilePhone,telephone,title,company,address,url,email,fax;
	private Card card;
	private DBApi dbApi;
	private boolean fromMain = false;
	private ImageView avatar;
	private Bitmap avatatBitmap ;
	private View voide_layout;
	private ToggleButton voideButton;
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_card);
		fromMain = getIntent().getBooleanExtra("fromMain", false);
		initView();
		initData();
	}
	private void initData() {
		if(card == null){
			showToast("您还没有个人信息，请新建一个");
			startActivityForResult(new Intent(this,EditCardInfoActivity.class).putExtra("card", card).putExtra("type", "add").putExtra("addMe", true),30001);
		}else{
			name.setText(card.getName());
			mobilePhone.setText(card.getMobilePhone());	
			telephone.setText(card.getTelephone());	
			title.setText(card.getTitle());	
			company.setText(card.getCompany());	
			address.setText(card.getAddress());	
			url.setText(card.getUrl());	
			email.setText(card.getEmail());	
			fax.setText(card.getFax());	
			
			if(!"".equals(card.getAvatar())){
				avatatBitmap = BitmapFactory.decodeFile(card.getAvatar());
				if(avatatBitmap!=null){
					avatar.setImageBitmap(avatatBitmap );
				}else{
					showToast("头像丢失");
				}
			}
			if(!"".equals(card.getVoide())){
				voide_layout.setVisibility(View.VISIBLE);
			}
		}
	}
	@Override
	protected void initView() {
		super.initView();
		dbApi = DBApi.getInstance(this);
		
		voide_layout =  findViewById(R.id.voide_layout);
		avatar = (ImageView) findViewById(R.id.avatar);
		name = (TextView) findViewById(R.id.name);
		name.setTextIsSelectable(true);
		mobilePhone = (TextView) findViewById(R.id.mobilePhone);
		mobilePhone.setTextIsSelectable(true);
		telephone = (TextView) findViewById(R.id.telephone);
		telephone.setTextIsSelectable(true);
		title = (TextView) findViewById(R.id.title);
		title.setTextIsSelectable(true);
		company = (TextView) findViewById(R.id.company);
		company.setTextIsSelectable(true);
		address = (TextView) findViewById(R.id.address);
		address.setTextIsSelectable(true);
		url = (TextView) findViewById(R.id.url);
		url.setTextIsSelectable(true);
		email = (TextView) findViewById(R.id.email);
		email.setTextIsSelectable(true);
		fax = (TextView) findViewById(R.id.fax);
		fax.setTextIsSelectable(true);
		
		voideButton = (ToggleButton) findViewById(R.id.voideButton);
		voideButton.setOnCheckedChangeListener(this);
		
		edit = (Button) findViewById(R.id.edit);
		edit.setOnClickListener(this);
		send = (Button) findViewById(R.id.send);
		send.setOnClickListener(this);
		
		if(fromMain){
			card = dbApi.getMyCard();
			send.setVisibility(View.VISIBLE);
			// Get local Bluetooth adapter
	        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	        if (mBluetoothAdapter == null) {
	            Toast.makeText(this, "蓝牙功能不可用", Toast.LENGTH_LONG).show();
	        }
	        if (!mBluetoothAdapter.isEnabled()) {
	            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
	            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
	        // Otherwise, setup the chat session
	        }
	        mCardService = new BluetoothCardService(this, mHandler);
	        
		}else{
			card = (Card) getIntent().getSerializableExtra("card");
			edit.setText("删除");
		}
	}
	BluetoothCardService mCardService;
	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.edit:
			 byte[] out = null;
			mCardService.write(out);
//			if(fromMain){
//				startActivityForResult(new Intent(this,EditCardInfoActivity.class).putExtra("card", card),30001);
//			}else{
//				card.setIsDel("1");
//				dbApi.updateRecord(card);
//				showToast("删除到回收站");
//				this.finish();
//			}
			break;
		case R.id.send:
			startActivityForResult(new Intent(this,DeviceListActivity.class),30002);
			break;

		default:
			break;
		}
	}
	


    // Key names received from the BluetoothChatService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";
    
    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                switch (msg.arg1) {
                case BluetoothCardService.STATE_CONNECTED:
                	System.out.println("MainMyCardActivity.enclosing_method()   连上");
//                    mTitle.setText(R.string.title_connected_to);
//                    mTitle.append(mConnectedDeviceName);
//                    mConversationArrayAdapter.clear();
                    break;
                case BluetoothCardService.STATE_CONNECTING:
                	System.out.println("MainMyCardActivity.enclosing_method()   正在连接");
//                    mTitle.setText(R.string.title_connecting);
                    break;
                case BluetoothCardService.STATE_LISTEN:
                case BluetoothCardService.STATE_NONE:
                	System.out.println("MainMyCardActivity.enclosing_method()   连接失败");
//                    mTitle.setText(R.string.title_not_connected);
                    break;
                }
                break;
            case MESSAGE_WRITE:
//                byte[] writeBuf = (byte[]) msg.obj;
                // construct a string from the buffer
//                String writeMessage = new String(writeBuf);
//                mConversationArrayAdapter.add("Me:  " + writeMessage);
                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg1);
//                mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
                break;
            case MESSAGE_DEVICE_NAME:
            	System.out.println("MainMyCardActivity.enclosing_method()   MESSAGE_DEVICE_NAME    "+msg.getData().getString(DEVICE_NAME));
                // save the connected device's name
                break;
            case MESSAGE_TOAST:
//                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
//                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };
    

    private static final int REQUEST_ENABLE_BT = 2;
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == 30001 && resultCode == 20001){
			card = (Card) data.getSerializableExtra("card");
			initData();
		}else if(requestCode == 30002 && resultCode == RESULT_OK){
			  // Get the device MAC address
            String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
            // Get the BLuetoothDevice object
            BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
            // Attempt to connect to the device
            mCardService.connect(device);
            System.out.println("MainMyCardActivity.onActivityResult()   "+address);
		}else if(requestCode == REQUEST_ENABLE_BT){
			if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
               System.out.println("MainMyCardActivity.onActivityResult()   OK");
            } else {
                // User did not enable Bluetooth or an error occured
            	showToast("蓝牙发送功能不能使用");
            }
		}else{
			card = dbApi.getMyCard();
			if(card == null){
				this.finish();
			}
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(avatatBitmap!=null){
			avatatBitmap.recycle();
		}
		stopAudio(mMediaPlayer);
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		voideButton.setChecked(false);
		stopAudio(mMediaPlayer);
	}	
	MediaPlayer mMediaPlayer = null;
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if(buttonView.getId() == R.id.voideButton){
			if(isChecked){
//				if(mMediaPlayer!=null){
//					mMediaPlayer.setOnCompletionListener(null);
//				}
//				stopAudio(mMediaPlayer);
//				File file = new File(CardApplication.getAudioRootDir(),card.getVoide());
				File file = new File(card.getVoide());
				if(file.exists()){
					Uri uri = Uri.fromFile(file);
					mMediaPlayer = MediaPlayer.create(this, uri);
					if(mMediaPlayer!=null){
						mMediaPlayer.start();
						mMediaPlayer.setOnCompletionListener(new CompletionListener());
					}else{
						showToast("音频有问题，请重新录制");
					}
				}else{
					voideButton.setChecked(false);
					showToast("音频丢失");
				}
			}else{
				stopAudio(mMediaPlayer);
			}
		}
	}
	
	public void stopAudio(MediaPlayer mp) {
		try {
			if(mp!=null){
				mp.stop();
				mp.release();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	class CompletionListener implements OnCompletionListener {
		@Override
		public void onCompletion(MediaPlayer mp) {
			voideButton.setChecked(false);
			stopAudio(mp);
		}
	}
}
